package com.sc.nft.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sc.nft.dao.EcologyPoolPrizeDao;
import com.sc.nft.entity.EcologyPoolPrize;
import com.sc.nft.enums.EcologyPoolLinkTypeEnum;
import com.sc.nft.enums.EcologyPoolPrizeBindTypeEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.EcologyPoolPrizeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 刘国航
 * @since 2024/8/10 17:23
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EcologyPoolPrizeServiceImpl implements EcologyPoolPrizeService {

    private final EcologyPoolPrizeDao ecologyPoolPrizeDao;


    @Override
    public void reducePrize(EcologyPoolPrize ecologyPoolPrize) {
        EcologyPoolPrize e = new EcologyPoolPrize();
        e.setRemainCount(BigDecimal.ZERO);
        LambdaUpdateWrapper<EcologyPoolPrize> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(EcologyPoolPrize::getId, ecologyPoolPrize.getId());
        updateWrapper.eq(EcologyPoolPrize::getVersion, ecologyPoolPrize.getVersion());
        ecologyPoolPrizeDao.update(e, updateWrapper);
    }

    @Override
    public void savePrize(EcologyPoolPrize prize) {
        boolean save = ecologyPoolPrizeDao.save(prize);
        if (!save) {
            throw new GlobalRunTimeException("新增配置异常");
        }
    }

    @Override
    public EcologyPoolPrize getEcologyPoolPrizeByBindId(Long bindId, EcologyPoolPrizeBindTypeEnum ecologyPoolPrizeBindTypeEnum, EcologyPoolLinkTypeEnum ecologyPoolLinkTypeEnum) {
        return ecologyPoolPrizeDao.getPrizeById(bindId, ecologyPoolPrizeBindTypeEnum, ecologyPoolLinkTypeEnum);
    }

    @Override
    public Map<Long, EcologyPoolPrize> listPrizeByIdsToMap(List<Long> ids, EcologyPoolPrizeBindTypeEnum ecologyPoolPrizeBindTypeEnum, EcologyPoolLinkTypeEnum ecologyPoolLinkTypeEnum) {
        List<EcologyPoolPrize> ecologyPoolPrizes = ecologyPoolPrizeDao.listPrizeByIds(ids, ecologyPoolPrizeBindTypeEnum, ecologyPoolLinkTypeEnum);
        if (CollectionUtils.isEmpty(ecologyPoolPrizes)) {
            return new HashMap<>();
        }
        return ecologyPoolPrizes.stream().collect(Collectors.toMap(EcologyPoolPrize::getBindId, x -> x));
    }
}
